import RadioModel from "@/views/components/UIModal/RadioModel";
import ProgressModal from "@/views/components/UIModal/ProgressModal";
import ResultModal from "@/views/components/UIModal/ResultModal";
import { useState, useEffect } from "react";
import { message, Button } from "antd";
import Typography from "@/pages/OrderModule/common/components/Typography";

import { SYNC_STOCK_TYPES } from "@/views/utils/constant";

import { usePolling } from "@/views/hooks/usePolling";

import { getInventorySyncGetSchedule } from "../../../service";

/**上传商品编码 */
function ActionModal(props) {
	// console.log("ActionModal(props)", props);
	const { selectedRows, isSkuType, title, commandText, alert } = props;
	const [visible, setVisible] = useState("RadioModel");
	const [percent, setPercent] = useState(0);

	const [result, setResult] = useState({ total: "--", success: "--", failed: "--" });

	const { setTimer, clearTimer } = usePolling();

	useEffect(() => {
		return () => {
			// console.log("ActionEnableSynchronizedInventoryModal 销毁时，清空计时器");
			clearTimer();
		};
	}, []);

	const onCancel = () => {
		props.onCancel();
		clearTimer();
	};

	const onFinish = ({ value }) => {
		const isSyncInventory = title == "禁止同步库存" ? 0 : 1;
		const syncType = title == "禁止同步库存" ? null : value;
		const data = {
			params: {
				ids: selectedRows.map(e => e.id),
				isSyncInventory: isSyncInventory, //是否同步库存：1,开启；0，关闭
				syncType: syncType //同步类型：1,可用；2,虚拟
			},
			isSkuType
		};
		props.handleCommand(commandText, data, ({ success, data }) => {
			// commandText="禁止同步库存确认后"
			//  commandText="开启同步库存确认后"
			// commandText="手动同步库存"

			console.log(commandText, data);
			if (title == "手动同步库存") {
				setVisible("ProgressModal");
				console.log(data);
				if (success) {
					setTimer(
						getInventorySyncGetSchedule,
						{ batchId: data },
						({ completedNum, isCompleted, totalNum }) => {
							if (isCompleted) {
								console.log("isCompleted");
								setVisible("ResultModal");
								setResult({ total: totalNum, success: completedNum, failed: totalNum - completedNum });
								return true;
							} else {
								console.log("setPercent");
								setPercent(((completedNum ? completedNum : 0 / totalNum ? totalNum : 0) * 100).toFixed());
								return false;
							}
						},
						() => {
							onCancel();
						}
					);
				} else {
					message.warning("提交失败");
				}
			}

			if (title == "开启同步库存" || title == "禁止同步库存") {
				if (isSkuType) {
					onCancel();
				} else {
					const { spuCount, skuCount, successCount, failCount, failSkuCodes } = data;
					setVisible("ResultModalAutoSpu");
					setResult({ spuCount, skuCount, successCount, failCount, failSkuCodes });
				}
			}
		});
	};
	const options = title == "禁止同步库存" ? null : SYNC_STOCK_TYPES;

	const ResultCom = ({ spuCount, skuCount, successCount, failCount, failSkuCodes }) => {
		return (
			<>
				<Typography>
					商品共：{spuCount || "-"} 款 {skuCount || "-"} sku
				</Typography>
				<Typography>
					成功：<span className="green">{successCount || 0}</span> sku
				</Typography>
				<Typography>
					失败：<span className="red">{failCount || 0}</span> sku
				</Typography>
			</>
		);
	};
	const ButtonCom = ({ spuCount, skuCount, successCount, failCount, failSkuCodes }) => {
		if (Array.isArray(failSkuCodes) && failSkuCodes.length) {
			const handleLink = () => {
				console.log("失败的sku，点击查看，根据失败的sku编码，跳转至店铺商品sku进行搜索展示", failSkuCodes);
				props.handleCommand("跳转SKU列表，按query刷新列表", { skuCode: failSkuCodes.join(",") });
				onCancel();
			};
			return (
				<Button className="height24" size="middle" type="primary" onClick={handleLink}>
					查看
				</Button>
			);
		} else {
			<></>;
		}
	};

	return (
		<>
			<RadioModel
				storageKey={"-commandText-" + title}
				title={"提示"}
				alert={alert}
				visible={visible === "RadioModel"}
				onCancel={onCancel}
				onOk={onFinish}
				options={options}
				tipsRender={() => (
					<span style={{ marginRight: "10px" }}>
						当前勾选生效商品数: <span className="red">{selectedRows.length}</span>
					</span>
				)}
			/>
			<ProgressModal
				visible={visible === "ProgressModal"}
				type="progress"
				percent={percent}
				skip={true}
				msg="批量更新中..."
				onCancel={() => {
					{
						onCancel();
					}
				}}
			/>

			<ResultModal
				visible={visible === "ResultModal"}
				onCancel={onCancel}
				onOk={() => setVisible("----")}
				result={result}
				isSkuType={isSkuType}
				actionType={"sync-stock-by-hand"}
			/>
			<ResultModal
				visible={visible === "ResultModalAutoSpu"}
				onCancel={onCancel}
				onOk={() => setVisible("----")}
				isSkuType={isSkuType}
				resultRender={() => <ResultCom {...result} />}
				buttonRender={() => <ButtonCom {...result} />}
			/>
		</>
	);
}

export default ActionModal;
